package cn.spike.org.service.impl;

import cn.spike.basic.service.impl.BaseServiceImpl;
import cn.spike.org.domain.Department;
import cn.spike.org.mapper.DepartmentMapper;
import cn.spike.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：部门
 * @author:sea
 * @create:2023-01-09 12:53
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> getDeptTree() {
        //1.获取所有的部门数据 放到map中，方便查找 - 执行合理，提高效率
        //1.1key放id，vlue是部门信息 - 方便通过map中的get方法通过id找出部门
        Map<Long, Department> map = new HashMap<>();
        //1.2查找出所有部门的信息
        List<Department> departments = departmentMapper.loadAll();
        //1.3遍历放入map中
        for (Department department : departments) {
            map.put(department.getId(),department);
        }
        //2.遍历出所有部门 判断是否有上级部门id
        List<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            //2.1 如果没有上级部门id - 说明是顶级部门 - 直接放入部门树中
            if(department.getParent_id()==null){
                deptTree.add(department);
            }else {
                //2.2 如果有上级部门id 通过上级部门id找到上级部门 获取上级部门的children属性 - 将自己添加进去
                Department parentDepartment = map.get(department.getParent_id());//获取到上级部门
                if(parentDepartment!=null){//判断如果删除了上级部门 部门为null导致空指针异常
                    parentDepartment.getChildren().add(department);//获取上级部门的children属性 - 将自己添加进去
                }
            }
        }
        return deptTree;
    }
}
